package test.dialogs.pages;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.window.Window;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;

import com.ahmedmisbah.andgenplus.constants.GlobalConstants;
import com.ahmedmisbah.andgenplus.restgenerator.beans.ListMapper;
import com.ahmedmisbah.andgenplus.restgenerator.beans.Mapper;
import com.ahmedmisbah.andgenplus.restgenerator.beans.RESTWebServiceDescriptor;
import com.ahmedmisbah.andgenplus.restgenerator.generator.RESTCodeGenerator;
import com.ahmedmisbah.andgenplus.utils.pde.PDEUtil;

public class RESTWizardPageTwo extends WizardPage implements Listener {

	private Composite parent;
	private GridData gridData;

	private boolean pageRendered;

	private ICompilationUnit[] pojoClasses;

	private Combo pojoClassesCombo;
	private Combo listSetterMethods;

	private Combo titleSetterMethods;
	private Combo imageSetterMethods;

	private String[] listGetterMethodsArray;

	private String[] pojoGetterMethodsArray;

	public RESTWizardPageTwo() {
		super("Step 2");
		setTitle("Step 2/2");
		setDescription("This page generates Android Activity and its files");
	}

	@Override
	public void createControl(Composite shellComposite) {
		// TODO Auto-generated method stub
		parent = new Composite(shellComposite, SWT.NULL);

		setControl(parent);
		setPageComplete(false);

		// Call this when you want to update
		// getWizard().getContainer().updateButtons();

	}

	public void renderPageItems() {

		if (!pageRendered) {
			GridLayout layout = new GridLayout();
			layout.numColumns = 3;
			parent.setLayout(layout);

			// The text fields will grow with the size of the dialog
			gridData = new GridData();
			gridData.grabExcessHorizontalSpace = true;
			gridData.horizontalAlignment = GridData.FILL;

			Label label0 = new Label(parent, SWT.NONE);
			label0.setText("List Setter");

			String pojoClassPath = (String) GlobalConstants.globalCache
					.get(GlobalConstants.POJO_PACKAGE_PATH);
			// String pojoClassPath="com.test.pojos";
			try {

				// pojoClasses=PDEUtil.getPackageClasses(pojoClassPath);
				pojoClasses = PDEUtil.getPackageClasses(pojoClassPath);

				String[] pojoClassNames = new String[pojoClasses.length];

				for (int i = 0; i < pojoClassNames.length; i++) {
					pojoClassNames[i] = pojoClasses[i].getElementName();
				}

				pojoClassesCombo = new Combo(parent, SWT.READ_ONLY);
				pojoClassesCombo.setItems(pojoClassNames);
				pojoClassesCombo.setLayoutData(gridData);
				pojoClassesCombo.addListener(SWT.Selection, (Listener) this);

				listSetterMethods = new Combo(parent, SWT.READ_ONLY);
				listSetterMethods.setLayoutData(gridData);
				listSetterMethods.addListener(SWT.Selection, (Listener) this);

				Label label1 = new Label(parent, SWT.NONE);
				label1.setText("(1) Label Setter");

				Label label2 = new Label(parent, SWT.NONE);
				label2.setText("");

				titleSetterMethods = new Combo(parent, SWT.READ_ONLY);
				titleSetterMethods.setLayoutData(gridData);

				Label label3 = new Label(parent, SWT.NONE);
				label3.setText("(2) Image Setter");

				Label label4 = new Label(parent, SWT.NONE);
				label4.setText("");

				imageSetterMethods = new Combo(parent, SWT.READ_ONLY);
				imageSetterMethods.setLayoutData(gridData);

				Label label5 = new Label(parent, SWT.NONE);
				label5.setText("");
				
				Label label7 = new Label(parent, SWT.NONE);
				label7.setText("");

				createGenerateCodeButton(parent, Window.OK, "Generate Code");

				Label label8 = new Label(parent, SWT.NONE);
				label8.setText("");

				// Add Image
				final String SCREEN1_IMAGE_PATH = GlobalConstants.WINDOWS_D_DRIVE
						+ File.separator
						+ GlobalConstants.AND_GEN_ROOT_FOLDER
						+ File.separator + GlobalConstants.SCREEN1_IMAGE;

				Label screenImage = new Label(parent, SWT.BORDER);
				screenImage.setImage(new Image(getShell().getDisplay(),
						SCREEN1_IMAGE_PATH));

				Label label6 = new Label(parent, SWT.NONE);
				label6.setText("");

				parent.layout();

				pageRendered = true;

			} catch (CoreException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

	public boolean isPageRendered() {
		return pageRendered;
	}

	public void setPageRendered(boolean pageRendered) {
		this.pageRendered = pageRendered;
	}

	@Override
	public void handleEvent(Event e) {
		if (e.widget == pojoClassesCombo) {
			int selectionIndex = pojoClassesCombo.getSelectionIndex();
			ICompilationUnit compilationUnit = pojoClasses[selectionIndex];
			try {
				List<IMethod> methods = PDEUtil.getIMethods(compilationUnit);
				List<String> getterMethods = new ArrayList<String>();
				for (IMethod method : methods) {
					if (method.getElementName().startsWith("get")) {
						getterMethods.add(method.getElementName());
					}
				}
				listGetterMethodsArray = new String[getterMethods.size()];
				listSetterMethods.setItems(getterMethods
						.toArray(listGetterMethodsArray));
			} catch (JavaModelException e1) {
				setErrorMessage(e1.getMessage());
			}

		} else if (e.widget == listSetterMethods) {
			int selectionIndex = listSetterMethods.getSelectionIndex();
			String listGetterMethod = listGetterMethodsArray[selectionIndex];
			String listPojoName = listGetterMethod.replaceAll("get", "");
			try {
				ICompilationUnit compilationUnit = PDEUtil.findClassByName(
						listPojoName, ".java");
				List<IMethod> methods = PDEUtil.getIMethods(compilationUnit);
				List<String> getterMethods = new ArrayList<String>();
				for (IMethod method : methods) {
					if (method.getElementName().startsWith("get")) {
						getterMethods.add(method.getElementName());
					}
				}

				pojoGetterMethodsArray = new String[getterMethods.size()];
				titleSetterMethods.setItems(getterMethods
						.toArray(pojoGetterMethodsArray));
				imageSetterMethods.setItems(getterMethods
						.toArray(pojoGetterMethodsArray));

			} catch (CoreException e1) {
				setErrorMessage(e1.getMessage());
			}

		}

	}

	private void createGenerateCodeButton(Composite parent, int id, String label) {

		Button button = new Button(parent, SWT.PUSH);
		button.setText(label);
		button.setFont(JFaceResources.getDialogFont());
		button.setData(new Integer(id));

		button.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent event) {

				try {
					generateAndroidScreen();
					setMessage("Classes generated successfully", INFORMATION);
					setPageComplete(true);
				} catch (Exception e) {
					e.printStackTrace();
					setErrorMessage(e.getMessage());
				}

			}
		});

	}

	private void generateAndroidScreen() throws Exception {

		validateInputs();

		RESTCodeGenerator generator = (RESTCodeGenerator) GlobalConstants.globalCache
				.get(GlobalConstants.REST_GENERATOR);

		RESTWebServiceDescriptor restDescriptor = generator.getRestDescriptor();

		String listGetterMethod = listSetterMethods.getItem(listSetterMethods
				.getSelectionIndex());
		String listPojoName = listGetterMethod.replaceAll("get", "");

		String pojoClassPackage = PDEUtil.findClassPackage(listPojoName,
				".java");


		Map<String, Mapper> mappers = restDescriptor.getMappers();

		ListMapper listMapper = new ListMapper();
		listMapper.setListPojoClassPath(pojoClassPackage);
		
		String titleSetterMethod=titleSetterMethods.getItem(titleSetterMethods.getSelectionIndex());
		String imageSetterMethod=imageSetterMethods.getItem(imageSetterMethods.getSelectionIndex());
		
		listMapper.setListSetter("."+listGetterMethod+"()");
		listMapper.setTitleSetter("."+titleSetterMethod+"()");
		listMapper.setImageSetter("."+imageSetterMethod+"()");

		mappers.put(GlobalConstants.LIST_MAPPER, listMapper);

		generator.generatePresentationCode();
		generator.finish();
	}

	private void validateInputs() throws Exception {

		if (listSetterMethods.getSelectionIndex() == -1) {
			throw new Exception("Please choose List Setter Method");
		}

		if (titleSetterMethods.getSelectionIndex() == -1) {
			throw new Exception("Please choose a Title Setter Method");
		}

		if (imageSetterMethods.getSelectionIndex() == -1) {
			throw new Exception("Please choose an Image Setter Method");
		}

	}

}
